package com.liyuxiang.graph.node;

import com.alibaba.cloud.ai.graph.OverAllState;
import com.alibaba.cloud.ai.graph.action.NodeAction;
import com.liyuxiang.graph.service.DepartmentRecommendationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DepartmentRecommendationNode implements NodeAction {
    
    private static final Logger logger = LoggerFactory.getLogger(DepartmentRecommendationNode.class);
    private final DepartmentRecommendationService departmentRecommendationService;
    
    public DepartmentRecommendationNode(DepartmentRecommendationService departmentRecommendationService) {
        this.departmentRecommendationService = departmentRecommendationService;
    }
    
    @Override
    public Map<String, Object> apply(OverAllState state) throws Exception {
        String userId = state.value("userId", "unknown");
        String query = state.value("query", "");
        Map<String, Object> symptoms = state.value("symptoms", new HashMap<>());
        List<String> history = state.value("conversationHistory", List.of());
        Integer questionCount = state.value("questionCount", 0);
        String intentType = state.value("intentType", "有意图");
        
        logger.info("开始AI科室推荐 - 用户ID: {}, 意图类型: {}, 症状数量: {}, 问诊轮次: {}", 
                userId, intentType, symptoms.size(), questionCount);
        logger.info("用户查询: {}", query);
        logger.info("收集到的症状信息: {}", symptoms);
        
        try {
            // 如果是直接挂号询问且症状信息为空，从查询中构建症状
            if ("直接挂号".equals(intentType) && symptoms.isEmpty()) {
                logger.info("直接挂号场景 - 从用户查询构建症状信息");
                symptoms = buildSymptomsFromQuery(query);
                logger.info("从查询构建的症状信息: {}", symptoms);
            }
            
            // 检查症状信息的完整性
            if (symptoms.isEmpty()) {
                logger.warn("症状信息为空，提供基础建议");
                Map<String, Object> result = new HashMap<>();
                result.put("recommendedDepartment", "内科");
                result.put("deptId", 0L);
                result.put("deptIds", new Long[]{0L});  // 添加科室ID数组支持
                result.put("response", "由于症状信息不够详细，建议您先到内科进行初步检查，医生会根据您的具体情况进一步确定诊疗方向。");
                result.put("isCompleted", true);
                result.put("confidence", 0.5);
                result.put("urgency", "medium");
                return result;
            }
            
            // 使用AI科室推荐服务
            DepartmentRecommendationService.DepartmentRecommendationResult recommendationResult = 
                    departmentRecommendationService.recommendDepartment(symptoms, history, questionCount, userId);
            
            // 构建详细的回复内容
            StringBuilder responseBuilder = new StringBuilder();
            
            if (recommendationResult.isEmergency()) {
                responseBuilder.append("【紧急】建议立即就医！\n\n");
            }
            
            responseBuilder.append("推荐科室：").append(recommendationResult.getPrimaryDepartment());
            
            // 处理多科室推荐显示
            if (recommendationResult.hasMultipleDepartments()) {
                responseBuilder.append("（共推荐").append(recommendationResult.getDeptIds().length).append("个科室）");
            }
            
            if (recommendationResult.getAlternativeDepartments().length > 0) {
                responseBuilder.append(" （备选：");
                responseBuilder.append(String.join("、", recommendationResult.getAlternativeDepartments()));
                responseBuilder.append("）");
            }
            responseBuilder.append("\n\n");
            
            responseBuilder.append("推荐理由：").append(recommendationResult.getReasoning()).append("\n\n");
            responseBuilder.append("就诊建议：").append(recommendationResult.getClinicalAdvice());
            
            if (recommendationResult.getRedFlags().length > 0) {
                responseBuilder.append("\n\n⚠️ 需要特别注意：");
                for (String redFlag : recommendationResult.getRedFlags()) {
                    responseBuilder.append("\n- ").append(redFlag);
                }
            }
            
            if (recommendationResult.getPreparationTips().length > 0) {
                responseBuilder.append("\n\n📋 就诊准备：");
                for (String tip : recommendationResult.getPreparationTips()) {
                    responseBuilder.append("\n- ").append(tip);
                }
            }
            
            String response = responseBuilder.toString();
            
            // 更新对话历史
            List<String> updatedHistory = new java.util.ArrayList<>(history);
            updatedHistory.add("系统推荐: " + response);
            
            // 记录详细的推荐信息，包括多科室信息
            logger.info("AI科室推荐结果 - 用户ID: {}, 主推科室: {}, 主科室ID: {}, 推荐科室数量: {}, 紧急度: {}, 置信度: {}", 
                    userId, recommendationResult.getPrimaryDepartment(), recommendationResult.getDeptId(), 
                    recommendationResult.getDeptIds() != null ? recommendationResult.getDeptIds().length : 0, 
                    recommendationResult.getUrgency(), recommendationResult.getConfidence());
            logger.info("推荐理由: {}", recommendationResult.getReasoning());
            logger.info("备选科室: {}", String.join("、", recommendationResult.getAlternativeDepartments()));
            
            if (recommendationResult.hasMultipleDepartments()) {
                logger.info("多科室推荐 - 科室IDs: {}", java.util.Arrays.toString(recommendationResult.getDeptIds()));
            }
            
            if (recommendationResult.isEmergency()) {
                logger.warn("检测到紧急情况 - 用户ID: {}, 推荐科室: {}", userId, recommendationResult.getPrimaryDepartment());
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("recommendedDepartment", recommendationResult.getPrimaryDepartment());
            result.put("deptId", recommendationResult.getDeptId());
            result.put("deptIds", recommendationResult.getDeptIds());  // 添加多科室ID数组
            result.put("alternativeDepartments", recommendationResult.getAlternativeDepartments());
            result.put("response", response);
            result.put("isCompleted", true);
            result.put("isEmergency", recommendationResult.isEmergency());
            result.put("confidence", recommendationResult.getConfidence());
            result.put("urgency", recommendationResult.getUrgency());
            result.put("reasoning", recommendationResult.getReasoning());
            result.put("clinicalAdvice", recommendationResult.getClinicalAdvice());
            result.put("redFlags", recommendationResult.getRedFlags());
            result.put("preparationTips", recommendationResult.getPreparationTips());
            result.put("estimatedWaitCategory", recommendationResult.getEstimatedWaitCategory());
            result.put("followUpSuggestions", recommendationResult.getFollowUpSuggestions());
            result.put("fullAiAnalysis", recommendationResult.isFullAiAnalysis());
            result.put("hasMultipleDepartments", recommendationResult.hasMultipleDepartments());  // 添加多科室标识
            result.put("conversationHistory", updatedHistory);
            
            logger.info("AI科室推荐完成 - 用户ID: {}, 最终推荐: {}, AI分析: {}", 
                    userId, recommendationResult.getPrimaryDepartment(), recommendationResult.isFullAiAnalysis());
            
            return result;
            
        } catch (Exception e) {
            logger.error("AI科室推荐失败 - 用户ID: {}, 错误: {}", userId, e.getMessage(), e);
            
            Map<String, Object> result = new HashMap<>();
            result.put("recommendedDepartment", "内科");
            result.put("deptId", 0L);
            result.put("deptIds", new Long[]{0L});  // 添加科室ID数组支持
            result.put("response", "系统暂时无法完整分析您的症状，建议您先到内科就诊，医生会为您做进一步的检查和诊断。如有急症，请直接前往急诊科。");
            result.put("error", e.getMessage());
            result.put("isCompleted", true);
            result.put("confidence", 0.4);
            result.put("urgency", "medium");
            result.put("fallback", true);
            
            logger.warn("使用默认科室推荐策略 - 内科");
            return result;
        }
    }
    
    /**
     * 从用户查询中构建症状信息，用于直接挂号场景
     */
    private Map<String, Object> buildSymptomsFromQuery(String query) {
        Map<String, Object> symptoms = new HashMap<>();
        String lowerQuery = query.toLowerCase();
        
        // 提取症状关键词
        if (lowerQuery.contains("头疼") || lowerQuery.contains("头痛")) {
            symptoms.put("主要症状", "头痛");
            symptoms.put("症状部位", "头部");
        } else if (lowerQuery.contains("胃痛") || lowerQuery.contains("胃疼")) {
            symptoms.put("主要症状", "胃痛");
            symptoms.put("症状部位", "胃部");
        } else if (lowerQuery.contains("腹痛") || lowerQuery.contains("肚子痛")) {
            symptoms.put("主要症状", "腹痛");
            symptoms.put("症状部位", "腹部");
        } else if (lowerQuery.contains("胸痛") || lowerQuery.contains("胸口痛")) {
            symptoms.put("主要症状", "胸痛");
            symptoms.put("症状部位", "胸部");
        } else if (lowerQuery.contains("发烧") || lowerQuery.contains("发热")) {
            symptoms.put("主要症状", "发热");
            symptoms.put("症状类型", "全身症状");
        } else if (lowerQuery.contains("咳嗽")) {
            symptoms.put("主要症状", "咳嗽");
            symptoms.put("症状部位", "呼吸道");
        } else if (lowerQuery.contains("腰痛")) {
            symptoms.put("主要症状", "腰痛");
            symptoms.put("症状部位", "腰部");
        } else {
            // 通用症状描述
            symptoms.put("主要症状", "用户描述的症状");
            symptoms.put("查询内容", query);
        }
        
        // 添加直接询问标识
        symptoms.put("直接询问", true);
        symptoms.put("原始查询", query);
        
        return symptoms;
    }
}